/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lct.eq2.backup;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 *
 * @author Me
 */
public class TestServer extends Thread {
    private ArrayList connectedThreads;
    
    public TestServer() {
        connectedThreads = new ArrayList();
    }
    
    @Override
    public void run() {
        System.out.println("Server started. Waiting for connections...");
        // Create a non-blocking server socket and check for connections
        ServerSocketChannel ssChannel = null;
        try {
            // Create a non-blocking server socket channel on port 80
            ssChannel = ServerSocketChannel.open();
            //ssChannel.configureBlocking(false);
            int port = 13267;
            ssChannel.socket().bind(new InetSocketAddress(port));
        } catch (IOException e) {
            //nothing
        }
        
        while (true) {
            try {
                SocketChannel sChannel = ssChannel.accept();
                if (sChannel != null) {
                    System.out.println("TestServer:: Client connected.");
                    TestServerThread thread = new TestServerThread(sChannel, this);
                    thread.start();
                    this.connectedThreads.add(thread);
                    
                }
            } catch (IOException e) {
                //nothing
            }
        }
    }
    
    public void sendData(Object o) {
        TestServerThread t = (TestServerThread)this.connectedThreads.get(0);
        t.sendData(o);
    }
    
    public void removeThread(Thread t) {
        this.connectedThreads.remove(t);
    }
}
